package com.suxin.webflux.service;


import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.netty.DisposableServer;
import reactor.netty.http.server.HttpServer;

import java.io.IOException;


public class Server {

    public static void main(String[] args) throws Exception {

        Server server = new Server();

        server.createReactiveServer();

        System.out.println( "server start..." );

        try {
            System.in.read();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private RouterFunction<ServerResponse> routingFunction() {

        UserServiceImpl userService = new UserServiceImpl();

        UserHandler userHandler = new UserHandler(userService);
        // 创建路由规则
        return RouterFunctions.route(
                RequestPredicates.GET("/user/get/{id}")
                        .and(RequestPredicates.accept(MediaType.APPLICATION_FORM_URLENCODED)),
                userHandler::getUserById
        ).andRoute(
                RequestPredicates.GET("/user/all")
                        .and(RequestPredicates.accept(MediaType.APPLICATION_JSON)),
                userHandler::getAll
        );

    }

    public void createReactiveServer() throws Exception {

        RouterFunction<ServerResponse> routerFunction = this.routingFunction();

        HttpHandler httpHandler = RouterFunctions.toHttpHandler(routerFunction);
        // 创建适配器
        ReactorHttpHandlerAdapter handlerAdapter = new ReactorHttpHandlerAdapter(httpHandler);

        HttpServer httpServer = HttpServer.create();

        // 绑定服务器
        DisposableServer server = httpServer.handle(handlerAdapter).bindNow();

        System.out.println("server port:--->" + server.port() );
    }

}
